package com.bwie.redkids.utils;

import java.util.ArrayList;

import com.bwie.redkids.base.CartSQLITE;
import com.bwie.redkids.bean.CartBean;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class CartDBUtils {

	private SQLiteDatabase db;

	public void openSQLite(Context context) {
		CartSQLITE sqlite = new CartSQLITE(context);
		db = sqlite.getReadableDatabase();
	}

	public void insert(CartBean cn) {
		db.execSQL("insert into cart(name_id,name,count,price,imageurl) values("
				+ cn.getName_id()
				+ ",'"
				+ cn.getName()
				+ "',"
				+ cn.getCount()
				+ "," + cn.getPrice() + ",'" + cn.getImageurl() + "')");
	}

	public void update(int name_id, CartBean cn) {
		int i = query(name_id);
		if (i != 0) {
			int count = i + cn.getCount();
			db.execSQL("update cart set count=" + count + " where name_id="
					+ name_id);
		} else {
			insert(cn);
		}
	}

	public void update(int name_id, int count) {
		db.execSQL("update cart set count=" + count + " where name_id="
				+ name_id);
	}

	public int query(int name_id) {
		Cursor c = db.rawQuery("select count from cart where name_id=?",
				new String[] { name_id + "" });
		if (c.moveToFirst()) {
			int i = c.getInt(c.getColumnIndex("count"));
			return i;
		}
		return 0;

	}

	/**
	 * 查询数据库中所有的已收藏状态的数据
	 * 
	 * @return
	 * @author 李杰 DBUtils ArrayList<CartBean>
	 */
	public ArrayList<CartBean> query() {
		ArrayList<CartBean> lt = new ArrayList<CartBean>();
		Cursor c = db.rawQuery("select * from cart", null);
		while (c.moveToNext()) {
			int name_id = c.getInt(c.getColumnIndex("name_id"));
			int count = c.getInt(c.getColumnIndex("count"));
			String name = c.getString(c.getColumnIndex("name"));
			double price = c.getDouble(c.getColumnIndex("price"));
			String imageurl = c.getString(c.getColumnIndex("imageurl"));
			CartBean CartBean = new CartBean(name_id, name, count, price,
					imageurl);
			lt.add(CartBean);
		}
		return lt;

	}

	public void closeSQLite() {
		db.close();
	}
}
